﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace DesignPattern.SingletonPattern
{
    //单例模式
    public class Singleton
    {
        #region 饿汉模式
        //饿汉模式,c#与java会有些不同
        //public static readonly Singleton instance = new Singleton();//内联初始化
        //private Singleton()
        //{
        //}
        //public static Singleton GetInstance()
        //{
        //    return instance;
        //} 
        #endregion


        #region 懒汉模式,需要锁
        //懒汉模式,只有在需要的时候才会加载
        private static volatile Singleton instance = null;
        private static object lockHelper = new Object();
        private Singleton() { }
        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                lock (lockHelper)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
        #endregion

        public long d1 = DateTime.Now.Millisecond;

        public void Print()
        {
            Console.WriteLine("当前线程:"+Thread.CurrentThread.ManagedThreadId+","+d1.ToString());
        }
    }
}
